<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Auth_model
 * @Auth Andy zhu
 * @Create 2015-12-22
 *
 */
class Auth extends  Db_model
{

  private  $id 			= 0;
  private  $user_info 	= array();


  function __construct(){
  		parent::__construct();
         $this->load->config('myconfig/site_config',true);
  }


  function get_auth_tree_json($group_id=0) {

		$g_condition  = array("id" => $group_id);
        $group   	  = $this->table_model->get_array_one("auth_group",$g_condition);
		if(!empty($group)){
     		$rules      = explode(",",$group["rules"]);
		}else{
			$rules 		= array();
		}

		$condition    = array("module"=>"home","status"=>1);
        $data   	  = $this->table_model->get_array("auth_rule",$condition);
		$arr    	  = array();
		$temp         = array();
		foreach($data  as $row){
			$temp["state"] = "open";
			$temp["id"] 		= $row["id"];
			$temp["text"] 		= $row["title"];
			$temp["level"] 		= $row["level"];
			if(in_array($row["id"], $rules) and $row["level"] >2 ){
				$temp["checked"] = "true";
			}
			if($row["level"] ==2 && $row["is_leaf"] ==0) {
				$temp["state"] = "closed";
			}
			$temp["parent_id"] 	= $row["parent_id"];
			$arr[]				= $temp;
			$temp =  array();
		}
		$result = arrtree($arr);
		$json_str = json_encode($result);
		echo  $json_str;

	}




      /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    public function get_user_info($uid) {
        static $userinfo=array();
        if(!isset($userinfo[$uid])){
             $condition  = array("id"=>$uid);
             $userinfo[$uid]= $this->table_model->get_array_one("user",$condition);
        }
        return $userinfo[$uid];
    }


      /**
     * 根据用户id获取用户组,返回值为数组
     * @param  uid int     用户id
     * @return array       用户所属的用户组 array(
     *     array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *     ...)
     */
    public function get_groups($uid) {
        static $groups = array();
        if (isset($groups[$uid]))
            return $groups[$uid];

        $this->db->select('uid,group_id,title,rules');
        $this->db->from('auth_group_access as a');
        $this->db->join('auth_group as b','b.id = a.group_id');
        $this->db->where(array('a.uid'=>$uid,"b.status"=>"1"));
        $user_groups =$this->db->get()->result_array();
        $groups[$uid]=$user_groups?:array();
        return $groups[$uid];
    }

   /**
     * 获得权限列表
     * @param integer $uid  用户id
     * @param integer $type
     */
    public function get_auth_list($uid,$type=1,$auth_type=1) {
        static $_authList = array(); //保存用户验证通过的权限列表

        $t = implode(',',(array)$type);
        if (isset($_authList[$uid.$t])) {
            return $_authList[$uid.$t];
        }
        if( $auth_type ==2 && isset($_SESSION['_AUTH_LIST_'.$uid.$t])){
            return $_SESSION['_AUTH_LIST_'.$uid.$t];
        }

        //读取用户所属用户组
        $groups = $this->get_groups($uid);

        $ids = array();//保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_authList[$uid.$t] = array();
            return array();
        }

        $map=array(
            'id'=>$ids,
            'type'=>$type,
            'status'=>1,
        );

        //读取用户组所有权限规则
        $this->db->select('condition,name');
        $this->db->from('auth_rule');
        $this->db->where_in("id", $ids);
        $this->db->where(array("status"=>"1"));
        $rules =$this->db->get()->result_array();
        //循环规则，判断结果。
        $authList = array();   //
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) { //根据condition进行验证
                $user = $this->get_user_info($uid);//获取用户信息,一维数组

                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                //dump($command);//debug
                @(eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid.$t] = $authList;
        if($auth_type == 2){
            //规则列表结果保存到session
            $_SESSION['_AUTH_LIST_'.$uid.$t]=$authList;
        }
        return array_unique($authList);
    }


    /**
      * 检查权限
      * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
      * @param uid  int           认证用户的id
      * @param string mode        执行check的模式
      * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
      * @return boolean           通过验证返回true;失败返回false
     */
    public function check($uid,$name,$relation='or', $type=1,$mode='url') {
    	$auth =$this->config->item('auth','myconfig/site_config');
        if (!$auth['auth_on'])
            return true;
        $authList = $this->get_auth_list($uid,$type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存验证通过的规则名
        if ($mode=='url') {
            $REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
        }
        foreach ( $authList as $auth ) {
            $query = preg_replace('/^.+\?/U','',$auth);
            if ($mode=='url' && $query!=$auth ) {
                parse_str($query,$param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST,$param);
                $auth = preg_replace('/\?.*$/U','',$auth);
                if ( in_array($auth,$name) && $intersect==$param ) {  //如果节点相符且url参数满足
                    $list[] = $auth ;
                }
            }else if (in_array($auth , $name)){
                $list[] = $auth ;
            }
        }
        if ($relation == 'or' and !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation == 'and' and empty($diff)) {
            return true;
        }
        return false;
    }


}
?>
